<!--
  * 物料入库记录表
  *
  * @Author:    yurui
  * @Date:      2024-07-30 16:00:02
  * @Copyright  jz
-->
<template>
  <a-modal
    :title="form.id ? '编辑' : '添加'"
    style="width: 1000px"
    :open="visibleFlag"
    @cancel="onClose"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
      <a-row>
        <a-col :span="12">
          <a-form-item label="出入库时间" name="inboundDate">
            <a-date-picker show-time valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="form.inboundDate" style="width: 80%" placeholder="出入库时间" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="出入库类型" name="type">
            <!-- @change="handleSensorTypeChange">change事件控制显示和隐藏  -->
            <a-select style="width: 80%" v-model:value="form.type" @change="handleSensorTypeChange">
              <a-select-option value="0">出库</a-select-option>
              <a-select-option value="1">入库</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="display">
          <a-form-item label="用料项目" name="projectId" required>
            <a-select style="width: 80%" v-model:value="form.projectId" placeholder="用料项目">
              <a-select-option v-for="item in MaterialProjectlist" :key="item" :value="item.id">{{ item.projectName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="分类" name="categoryId" required>
            <a-select style="width: 80%" v-model:value="form.categoryId" placeholder="分类" @change="referenceChange(form.categoryId)">
              <a-select-option v-for="item in dictValueList" :key="item" :value="item.categoryId">{{ item.categoryName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="物料" name="materialBaseId">
            <a-select
              style="width: 80%"
              v-model:value="form.materialBaseId"
              placeholder="物料"
              @change="material"
              @dropdownVisibleChange="handleChange"
            >
              <a-select-option v-for="item in wuliaoValueList" :key="item.id" :value="item.id">{{ item.materialName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="数量" name="quantity">
            <a-input-number style="width: 80%" v-model:value="form.quantity" placeholder="数量" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注" name="remark">
            <a-textarea style="width: 80%" v-model:value="form.remark" placeholder="备注" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick, watch } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { inventoryOperationsApi } from '/@/api/business/inventory-operations/inventory-operations-api';
  import { projectMaterialApi } from '/@/api/business/project-material/project-material-api';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { materialBaseApi } from '/@/api/business/material-base/material-base-api';
  // import BooleanSelect from '/@/components/framework/boolean-select/index.vue';

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);
  // 选择'出库' 控制 '用料项目框'的显示和隐藏
  const display = ref(false);
  function handleSensorTypeChange(e) {
    // console.log(e)
    if (e == 0) {
      display.value = true;
    } else {
      if (e == 1) {
        display.value = false;
      }
    }
  }
  const classify = ref([]);
  // 用料项目
  const MaterialProjectlist = ref([]);
  async function MaterialProject1() {
  let res = await inventoryOperationsApi.materialProject();
  // console.log(res);
  MaterialProjectlist.value = res.data;
  }
  //-----------------显示与隐藏 ---------------
  // 是否显示
  const visibleFlag = ref(false);
  function show(rowData) {
    //打开编辑赋值
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    queryDict2();
    MaterialProject1();
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
}
// ----------------------------------------------------
function show1(rowData) {
  //分类
  console.log(classify.value.get(rowData.materialBaseId));
  rowData.categoryId = classify.value.get(rowData.materialBaseId).categoryId;
  referenceChange(rowData.categoryId);
    //打开编辑赋值
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    queryDict2();
    MaterialProject1();
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
    wuliaoValueList.value = [];
  }
  // ------------------------ 表单 ------------------------
  //分类校验
  // const handleChange = ref([]);
  function handleChange(e) {
    // formRef.value.resetFields();
    console.log(e);
    if (wuliaoValueList.value.length == 0) {
      message.warn('请先选择分类');
    }
  }
  //点击分类传参 点击物料选择
  const wuliaoValueList = ref([]);
  async function referenceChange(id) {
    // console.log(id);
    let obj = {
      categoryId: id,
    };
    let res = await projectMaterialApi.ClassificationReference(obj);
    console.log(res);
    wuliaoValueList.value = res.data;
  }
  // 分类
  const formDefault1 = reactive({
    categoryType: 2,
  // parentId:''
  });
  const dictValueList = ref([]);
  async function queryDict2() {
    let res = await projectMaterialApi.ClassificationData(formDefault1);
    dictValueList.value = res.data;
    // console.log(res);
}
  
  //初始化页面数据
  async function initDate() {
    let res = await materialBaseApi.queryPage({ pageNum: 1, pageSize: 10 });
    classify.value = res.data.list;
    const listToMap = () => {
      return res.data.list.reduce((map, item) => {
        map.set(item.id, item);
        return map;
      }, new Map());
    };
    classify.value = listToMap();

    console.log(classify);
  }
  initDate();

  // 组件ref
  const formRef = ref();

  const formDefault = {
    id: undefined,
    inboundDate: undefined, //出入库时间
    type: undefined, //出入库类型（0出库，1入库）
    materialBaseId: undefined, //物料
    quantity: undefined, //数量
    remark: undefined, //备注
    categoryId: undefined, //分类
    projectName: undefined, //物料名称
    projectId: undefined,
  };

  let form = reactive({ ...formDefault });

  const rules = {
    inboundDate: [{ required: true, message: '出入库时间 必填' }],
    type: [{ required: true, message: '出入库类型 必填' }],
    // materialBaseId: [{ required: true, message: '物料 必填' }],
    quantity: [{ required: true, message: '数量 必填' }],
    remark: [{ required: true, message: '备注 必填' }],
    categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
    materialBaseId: [{ required: true, message: '请先选择分类', trigger: 'change' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    console.log(form);
    try {
      await formRef.value.validateFields();

      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      if (form.id) {
        await inventoryOperationsApi.update(form);
      } else {
        await inventoryOperationsApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  defineExpose({
    show,show1
  });
</script>
